package mashibing.class1;

/**
 * 局部最小值（二分法）
 *
 * @author yujiafan
 * @version 1.0.0
 * @create 2023-03-04
 */
public class Class1_5_LocalMinValue {

    public static int localMinValue(int[] arr) {
        if (arr == null || arr.length == 0) return -1;
        if (arr.length == 1) return 0;
        if (arr[0] < arr[1]) return 0;
        int length = arr.length;
        if (arr[length - 1] < arr[length - 2]) {
            return length - 1;
        }
        int L = 0;
        int R = length - 1;
        int mid = (L + R) / 2;
        while (L <= R) {
            if (arr[mid] > arr[mid - 1]) {
                R = mid - 1;
            } else if (arr[mid] > arr[mid + 1]) {
                L = mid + 1;
            } else {
                return mid;
            }
            mid = (L + R) / 2;
        }
        throw new RuntimeException("出错了");
    }

    public static void main(String[] args) {
        int[] arr = {8, 5, 3, 9, 8, 6, 2, 5};
        System.out.println(localMinValue(arr));
    }
}
